﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Web.Configuration;
using System.Web.UI.HtmlControls;

namespace ForestryEnterprise
{
    public partial class TreeShop : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.buyType.Items.Add(new ListItem("Cube Meter", "1"));
                this.buyType.Items.Add(new ListItem("Area Meter", "2"));

                this.trees.Items.Add(new ListItem("--->"));
                string statement = "select tree_id, tree_name from Tree";
                OleDbConnection connection = new OleDbConnection(WebConfigurationManager.ConnectionStrings["forestryDB"].ConnectionString);
                OleDbCommand command = new OleDbCommand(statement, connection);

                connection.Open();
                OleDbDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    ListItem newTree = new ListItem(reader["tree_name"].ToString(), reader["tree_id"].ToString());
                    this.trees.Items.Add(newTree);
                }

                reader.Close();
                connection.Close();
            }
        }

        protected void addTree_Click(object sender, EventArgs e)
        {
            Invoice currInv;

            if (Session["currentInvoice"] == null)
            {
                currInv = new Invoice();
            }
            else
            {
                currInv = (Invoice)Session["currentInvoice"];
            }

            Subinvoice sub = currInv.getSubinvoice(int.Parse(this.trees.SelectedValue));

            if (sub != null)
            {
                sub.Amount += int.Parse(this.treeAmount.Text);
            }
            else
            {
                Subinvoice subInv = new Subinvoice(int.Parse(this.treeAmount.Text), int.Parse(this.buyType.SelectedValue), int.Parse(this.trees.SelectedValue));
                currInv.addSubinvoice(subInv);
            }
            Session["currentInvoice"] = updateInvoiceView(currInv);
        }

        private Invoice updateInvoiceView(Invoice inv)
        {
            foreach (Subinvoice sub in inv.getSubinvoices())
            {
                string statement = "select tree_name from Tree where tree_id = " + sub.TreeID;
                OleDbConnection connection = new OleDbConnection(WebConfigurationManager.ConnectionStrings["forestryDB"].ConnectionString);
                OleDbCommand command = new OleDbCommand(statement, connection);
                connection.Open();
                OleDbDataReader reader = command.ExecuteReader();
                reader.Read();
                string treeName = reader["tree_name"].ToString();
                reader.Close();
                connection.Close();

                HtmlTableRow row = new HtmlTableRow();

                HtmlTableCell name = new HtmlTableCell();
                name.InnerText = treeName;

                HtmlTableCell amount = new HtmlTableCell();
                amount.InnerText = sub.Amount.ToString();

                HtmlTableCell costPer = new HtmlTableCell();
                costPer.InnerText = sub.Cost.ToString();

                HtmlTableCell totalCost = new HtmlTableCell();
                totalCost.InnerText = (sub.Cost * sub.Amount).ToString();

                row.Controls.Add(name);
                row.Controls.Add(amount);
                row.Controls.Add(costPer);
                row.Controls.Add(totalCost);
                this.subinvs.Controls.Add(row);
            }

            return inv;
        }

        protected void cancel_Click(object sender, EventArgs e)
        {
            Session.Remove("currentInvoice");
            Response.Redirect("Tree.aspx");
        }

        protected void buy_Click(object sender, EventArgs e)
        {
            //Extract invoice from session
            Invoice inv = (Invoice)Session["currentInvoice"];
            Session.Remove("currentInvoice");

            //write invoice in table
            string statement = "insert into Invoice(i_dueDate, p_ide, p_idc, i_dateprint, i_totalCost, i_amountM3, i_amountPrm) ";
            statement += "values(@dueDate, @pIDE, @pIDC, @datePrint, @totalCost, @amountM3, @amountPrm)";
            OleDbConnection connection = new OleDbConnection(WebConfigurationManager.ConnectionStrings["forestryDB"].ConnectionString);
            OleDbCommand command = new OleDbCommand(statement, connection);
            command.Parameters.AddWithValue("@dueDate", DateTime.Now.AddMonths(2).ToShortDateString());
            command.Parameters.AddWithValue("@pIDE", 2);//get from session (who accepts the invoice)
            command.Parameters.AddWithValue("@pIDC", 2);//get client from session
            command.Parameters.AddWithValue("@datePrint", DateTime.Now.ToShortDateString());
            command.Parameters.AddWithValue("@totalCost", inv.TotalCost);
            command.Parameters.AddWithValue("@amountM3", inv.AmountM3);
            command.Parameters.AddWithValue("@amountPrm", inv.AmountPRM);
            connection.Open();
            command.ExecuteNonQuery();
            connection.Close();

            //get last inserted invoice's id
            statement = "select top 1 i_id from Invoice order by i_id desc";
            command = new OleDbCommand(statement, connection);
            connection.Open();
            OleDbDataReader reader = command.ExecuteReader();
            reader.Read();
            int lastInvoice = int.Parse(reader["i_id"].ToString());
            reader.Close();
            connection.Close();

            //write subinvoices in table
            statement = "insert into SubInvoice(si_amount, si_buyType, i_id, tree_id) ";
            statement += "values(@amount, @bType, @iID, @treeID)";

            foreach (Subinvoice sub in inv.getSubinvoices())
            {
                command = new OleDbCommand(statement, connection);
                command.Parameters.AddWithValue("@amount", sub.Amount);
                command.Parameters.AddWithValue("@bType", sub.BuyType == 1 ? "m3" : "prm");
                command.Parameters.AddWithValue("@iID", lastInvoice);
                command.Parameters.AddWithValue("@treeID", sub.TreeID);
                connection.Open();
                command.ExecuteNonQuery();
                connection.Close();
            }

            Response.Redirect("Tree.aspx");
        }
    }
}